//
//  JFBGlobalSetting.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/17.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "JFBGlobalSetting.h"
#import "StorageSetting.h"
#import "JFBBaseStorage.h"
#import "MiPushSDK.h"
#import "AppDelegate.h"
#import "InterfaceURLConfig.h"

@interface JFBGlobalSetting()
@property(nonatomic, strong) StorageSetting *settingRecord;
@property (nonatomic, strong) JFBBaseStorage *store;
@end

@implementation JFBGlobalSetting
@synthesize appName, isLogin, ns, clientId, clientSecret, appVersion;
@synthesize rootURL;
@synthesize baseURL;
@synthesize version;

+ (JFBGlobalSetting*)getSetting
{
    static dispatch_once_t onceToken;
    static JFBGlobalSetting * sSharedInstance;
    dispatch_once(&onceToken, ^{
        sSharedInstance = [[JFBGlobalSetting alloc] init];
    });
    return sSharedInstance;
}

- (NSString*)getAccessToken {
    StorageSetting *setting = self.settingRecord;
    if(!setting) {
        return nil;
    }
    return setting.access_token;
}

- (NSUInteger)getShopId {
    StorageSetting *setting = self.settingRecord;
    if(!setting) {
        return 0;
    }
    return [setting.shop_id intValue];
}

- (StorageSetting*)getSettingRecord{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBSetting"];
    
    NSError *error;
    
    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
    
    if( array.count <= 0 ) {
        _settingRecord = nil;
    } else {
        _settingRecord = [array objectAtIndex:0];
    }
    return _settingRecord;
}

-(void)initializeUserInfoWithToken:(NSString*)token {
    // 初始化用户信息
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBSetting"];
    NSError *error;
    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
    StorageSetting *storeSetting;
     
    if( array.count <= 0 ) {
        storeSetting = (StorageSetting*)[NSEntityDescription insertNewObjectForEntityForName:@"JFBSetting" inManagedObjectContext:[_store managedObjectContext]];
    } else {
        storeSetting = [array objectAtIndex:0];
    }
    storeSetting.access_token = token;
//    storeSetting.shop_id = [NSNumber numberWithInteger:shopId];
    storeSetting.alertSound = true;
    
    BOOL isSuccess = [_store.managedObjectContext save:&error];
    if (isSuccess) {
        self.isLogin = YES;
        self.accessToken = token;
//        self.shopId = shopId;
        [((AppDelegate*)[UIApplication sharedApplication].delegate) registerForRemoteNotifications];
    }
}

-(Boolean)logout{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"JFBSetting"];
    NSError *error;
    NSArray *array = [_store.managedObjectContext executeFetchRequest:request error:&error];
    StorageSetting *storeSetting;
    if( array.count != 0 ) {
        storeSetting = [array objectAtIndex:0];
        [_store.managedObjectContext deleteObject:storeSetting];
        [_store.managedObjectContext save:&error];
    }
    [MiPushSDK unregisterMiPush];
    self.isLogin = NO;
    self.accessToken = @"";
    self.shopId = 0;
    
    return TRUE;
}

-(void)loadUserInfo{
    StorageSetting *obj = [self getSettingRecord];
    if (obj) {
        self.accessToken = obj.access_token;
        self.shopId = [obj.shop_id intValue];
        
        self.isLogin = YES;
    } else {
        // 需要登录
        self.isLogin = NO;
        self.accessToken = @"";
        self.shopId = 0;
    }
}

- (BOOL)updateSettingInfo:(NSString*)key value:(id)value {
    StorageSetting *obj = [self getSettingRecord];
    if(obj) {
        [obj setValue:value forKey:key];
        NSError *error;
        return [_store.managedObjectContext save:&error];
    }
    return NO;
}

- (id)getSettingInfo:(NSString*)key {
    StorageSetting *obj = [self getSettingRecord];
    if(obj) {
        return [obj valueForKey:key];
    }
    return nil;
}

- (id)init {
    self = [super init];
    if (self) {
        _store = [JFBBaseStorage getStore];
        
        NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"setting" ofType:@"plist"];
        
        self.rootURL = API_HOST;
        
        ZNLog(@"rooturl:%@", self.rootURL);
        
        NSDictionary *data = [NSDictionary dictionaryWithContentsOfFile:dataPath];

        self.appName = [data objectForKey:@"AppName"];
        self.baseURL = [data objectForKey:@"APIPrefix"];
        self.version = [data objectForKey:@"APIVersion"];
        self.clientSecret = [data objectForKey:@"ClientSecret"];
        self.clientId = [data objectForKey:@"ClientID"];
        self.appVersion = [data objectForKey:@"AppVersion"];
        self.ns = [data objectForKey:@"APINS"];
        self.defaultAnyCode = [data objectForKey:@"DefaultAnyCode"];
        
        self.isStoreStateChange = FALSE;
        
        [self loadUserInfo];
    }
    return self;
}

@end
